/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: FinanceRedemptionActivity.java
 *   @Date: 19-3-11 下午4:49
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.finance.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;

import java.math.BigDecimal;

import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.finance.presenter.FinanceRedemptionPresenter;
import io.bhex.app.utils.ActivityCache;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.PointLengthFilter;
import io.bhex.app.view.TopBar;
import io.bhex.app.web.ui.WebActivity;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.Urls;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.finance.bean.FinanceAssetDetailResponse;
import io.bhex.sdk.finance.bean.FinanceBean;
import io.bhex.sdk.finance.bean.WalletBean;

public class FinanceRedemptionActivity extends BaseActivity<FinanceRedemptionPresenter,FinanceRedemptionPresenter.FinanceRedemptionUI> implements FinanceRedemptionPresenter.FinanceRedemptionUI, View.OnClickListener {
    private TopBar topBar;
    private TextInputLayout amountTextInputLayout;
    private TextInputEditText amountTextInputEt;
    private PointLengthFilter amountPointFilter;
    private Button btnRedeem;
    private String productId;
    private FinanceBean financeBean;
    private FinanceAssetDetailResponse currentFinanceAsset;
    private WalletBean currentWallet;
    private View btnClear;

    @Override
    protected int getContentView() {
        return R.layout.activity_finance_redemption_layout;
    }

    @Override
    protected FinanceRedemptionPresenter createPresenter() {
        return new FinanceRedemptionPresenter();
    }

    @Override
    protected FinanceRedemptionPresenter.FinanceRedemptionUI getUI() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCache.getInstance().addFinanceActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCache.getInstance().removeFinanceActivity(this);
    }

    @Override
    protected void initView() {
        super.initView();
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        Intent intent = getIntent();
        if (intent != null) {
            productId = intent.getStringExtra("productId");
        }
        amountTextInputLayout = viewFinder.find(R.id.purchase_amount_il);
//        amountTextInputLayout.getEditText().setHintTextColor(SkinColorUtil.getDark80(this));
        amountTextInputEt = viewFinder.find(R.id.purchase_amount_iet);
        btnClear = viewFinder.find(R.id.input_clear);
        btnRedeem = viewFinder.find(R.id.btn_redeem);
        amountPointFilter = new PointLengthFilter();
        amountPointFilter.setDecimalLength(2);
        amountTextInputEt.setFilters(new InputFilter[]{amountPointFilter});
    }


    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.btn_all).setOnClickListener(this);
        viewFinder.find(R.id.btn_redeem).setOnClickListener(this);
        viewFinder.find(R.id.input_clear).setOnClickListener(this);
        amountTextInputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    btnRedeem.setEnabled(false);
                    btnClear.setVisibility(View.GONE);
                }else{
                    btnRedeem.setEnabled(true);
                    btnClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(productId)) {
            getPresenter().getAsset(productId);
        }
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    public void showAsset(FinanceAssetDetailResponse response) {
        if (response != null) {
            currentFinanceAsset = response;
            financeBean = response.getProduct();
            currentWallet = response.getWallet();
            int tradeScale = NumberUtils.calNumerCount(this, financeBean.getTradeScale());
            amountPointFilter.setDecimalLength(tradeScale);
            if (financeBean != null) {
                viewFinder.textView(R.id.redeem_amount_title).setText(getString(R.string.string_finance_redemption_amount)+"("+financeBean.getToken()+")");
            }
            if (currentWallet != null) {
                viewFinder.textView(R.id.surplusAmount).setText(getString(R.string.string_finance_can_redeem_amount)+" "+NumberUtils.roundFormatDown(currentWallet.getAvailable(),tradeScale)+" "+financeBean.getToken());
            }

        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.input_clear:
                amountTextInputEt.setText("");
                break;
            case R.id.btn_all:
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TRADE)) {
                    if (currentWallet != null) {
                        amountTextInputEt.setText(currentWallet.getAvailable());
                    }
                }
                break;
            case R.id.agreement_finance:
//                agreeCb.setChecked(!agreeCb.isChecked());
                WebActivity.runActivity(this,"",Urls.H5_URL_FINANCE_SERVICE);
                break;

            case R.id.btn_redeem:
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TRADE)) {
                    if (financeBean != null) {

                        String amount = amountTextInputEt.getText().toString().trim();
                        if (TextUtils.isEmpty(amount)) {
                            amountTextInputLayout.setError(getString(R.string.string_input_please)+getString(R.string.string_finance_redemption_amount));
                            return;
                        }
                        String tradeMinAmount = financeBean.getRedeemMinAmount();
                        if (NumberUtils.sub(amount,tradeMinAmount)<0) {
//                            ToastUtils.showLong(getString(R.string.string_finance_no_less_min_trade_amount_format,tradeMinAmount,financeBean.getToken()));
                            amountTextInputLayout.setError(getString(R.string.string_finance_no_less_min_redeem_trade_amount_format,tradeMinAmount,financeBean.getToken()));
                            return;
                        }
                        String tradeScale = financeBean.getTradeScale();
                        if (new BigDecimal(amount).remainder(new BigDecimal(tradeScale)).compareTo(BigDecimal.ZERO)!=0) {
                            amountTextInputLayout.setError(getString(R.string.string_finance_input_trade_amount_must_integer_multiple_format,tradeScale));
                            return;
                        }
                        getPresenter().redeem(financeBean,amount);
                    }else{
                        ToastUtils.showLong(this,getString(R.string.string_data_exception));
                    }
                }
                break;
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
